<?php

namespace app\modules\models;

use Codeception\Command\SelfUpdate;
use Yii;
use yii\db\ActiveRecord;

class Admin extends ActiveRecord
{
    public $RememberMe = true;
    public $repass;

    public static function tableName()
    {
        return '{{%admin}}';
    }

    public function rules()
    {
        return [
            [['adminuser'], 'required', 'message' => '管理员账号不能为空', 'on' => ['login', 'seekpassword', 'addAdmin', 'updatePass']],
            [['adminpass'], 'required', 'message' => '管理员密码不能为空', 'on' => ['login', 'addAdmin', 'updatePass']],
            [['RememberMe'], 'boolean', 'on' => ['login']],
            [['adminpass'], 'required', 'on' => ['login', 'changePass', 'addAdmin']],
            [['adminpass'], 'checkPass', 'on' => ['login', 'updateEmail',]],
            [['adminemail'], 'unique', 'message' => '邮箱已被注册', 'on' => ['addAdmin', 'updateEmail']],
            [['adminuser'], 'unique', 'message' => '账户已被注册', 'on' => ['addAdmin']],
            [['adminemail'], 'required', 'message' => '邮箱不能为空', 'on' => ['seekpassword', 'addAdmin', 'updateEmail']],
            [['adminemail'], 'email', 'message' => '邮箱格式不正确', 'on' => ['seekpassword', 'addAdmin', 'updateEmail']],
            [['adminemail'], 'checkEmail', 'on' => 'seekpassword'],
            [['repass'], 'required', 'message' => '确认密码不能为空', 'on' => ['changePass', 'addAdmin', 'updatePass']],
            [['repass'], 'compare', 'compareAttribute' => 'adminpass', 'message' => '两次密码输入不一致', 'on' => ['changePass', 'addAdmin', 'updatePass']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'adminuser'  => '管理员账号',
            'adminemail' => '管理员邮箱',
            'adminpass'  => '管理员密码',
            'repass'     => '确认密码',
        ];
    }

    public function checkPass()
    {
        if (!$this->hasErrors()) {
            $bool = self::find()->where(['adminuser' => $this->adminuser, 'adminpass' => md5($this->adminpass)])->one();
            if (is_null($bool)) {
                $this->addError('adminpass', '用户名或密码错误');
            }
        }
    }

    public function checkEmail()
    {
        if (!$this->hasErrors()) {
            $data = self::find()->where(['adminuser' => $this->adminuser, 'adminemail' => $this->adminemail])->one();
            if (is_null($data)) {
                $this->addError('adminemail', '账号或邮箱不存在');
            }
        }
    }

    public function login($data)
    {
        $this->scenario = 'login';
        if ($this->load($data) && $this->validate()) {
            $lifetime = $this->RememberMe ? 3600 * 24 : 0;
            $session  = Yii::$app->session;
//            session_set_cookie_params($lifetime);
            $session->set($this->adminuser, [
                'adminuser' => $this->adminuser,
                'isLogin'   => 1,
            ]);
            $this->updateAll(['logintime' => time(), 'loginip' => ip2long(Yii::$app->request->userIP)], ['adminuser' => $this->adminuser]);
            return (bool)$session[$this->adminuser]['isLogin'];
        }
        return false;
    }

    public function seekPassword($data)
    {
        $this->scenario = 'seekpassword';
        if ($this->load($data) && $this->validate()) {
            $time   = time();
            $token  = $this->createToken($data['Admin']['adminuser'], $time);
            $mailer = Yii::$app->mailer->compose('seekpass', ['adminuser' => trim($data['Admin']['adminuser']), 'timestamp' => $time, 'token' => $token]);
            $mailer->setFrom('15267189004@163.com');
            $mailer->setTo($data['Admin']['adminemail']);
            $mailer->setSubject('找回密码');
            if ($mailer->send()) {
                return true;
            }
        }
        return false;
    }

    public function createToken($adminuser, $time)
    {
        return md5($adminuser . base64_encode(Yii::$app->request->userIP) . md5($time));
    }


    public function changePass($data)
    {
        $this->scenario = 'changePass';
        if ($this->load($data) && $this->validate()) {
            $adminuser = $data['Admin']['adminuser'];
            $pass      = $data['Admin']['repass'];
            if ($this->updateAll(['adminpass' => md5($pass)], ['adminuser' => $adminuser])) {
                return true;
            }
        }
        return false;
    }

    public function addAdmin($data)
    {
        $this->scenario = 'addAdmin';
        if ($this->load($data) && $this->validate()) {
            $this->adminpass = md5($this->adminpass);
            if ($this->save(false)) {
                return true;
            }
        }
        return false;
    }

    public function updateEmail($data)
    {
        $this->scenario = 'updateEmail';
        if ($this->load($data) && $this->save()) {
            return true;
        }
        return false;
    }

    public function updatePass($data)
    {
        $this->scenario = 'updatePass';
        if ($this->load($data) && $this->validate()) {
            $pass = md5($this->adminpass);
            return (bool)$this->updateAll(['adminpass' => $pass], ['adminuser' => $this->adminuser]);
        }
        return false;
    }
}